﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Workflow.Common.FileUtil;
using Workflow.Common;
using System.Configuration;

namespace Workflow.Web
{
    public partial class ViewTiff : System.Web.UI.Page
    {
        int DefaultThumbHieght = 100;
        int DefaultThumbWidth = 100;
        int DefaultBigHieght = 800;
        int DefaultBigWidth = 800;
        int PagerSize = 8;

        #region Tiff PreCache


        private String tifSuffix;

        //private String CreateTempTiff(String filePath){


        //    String tempTiffPath;

        //    //Check Child
        //    int child_num = 0;
        //    for (; ; child_num++)
        //    {
        //        tifSuffix = @"-" + (child_num + 1) + @".tif";

        //        if (!FileUtil.FileExist(filePath.Replace(@".tif", tifSuffix)))
        //            break;
        //    }


        //    //Check TempTiff
        //    String tmpBaseFolder = AppDomain.CurrentDomain.BaseDirectory + @"TempFiles"; //Temp Base Folder

        //    int tmpIndex;
        //    tmpIndex = filePath.LastIndexOf(@"\");

        //    String tmpFileName;
        //    tmpFileName = filePath.Substring(tmpIndex);

        //    if (child_num > 0)
        //        tmpFileName = tmpFileName.Replace(@".tif", @"-" + child_num + @".tif");

        //    tempTiffPath = tmpBaseFolder + tmpFileName;

        //    if (!FileUtil.FileExist(tempTiffPath))
        //    {

        //        try
        //        {

        //            MODI.Document dc_o = new MODI.Document();
        //            MODI.Document dc_d = new MODI.Document();

        //            dc_d.Create();
        //            dc_o.Create(filePath);
        //            for (int pageIndex = 0; pageIndex < dc_o.Images.Count; pageIndex++)
        //            {
        //                dc_d.Images.Add(((MODI.Image)dc_o.Images[pageIndex]), null);
        //            }

        //            dc_o.Close();

        //            for (int i = 1; i <= child_num; i++)
        //            {
        //                dc_o.Create(filePath.Replace(@".tif", @"-" + i + @".tif"));
        //                for (int pageIndex = 0; pageIndex < dc_o.Images.Count; pageIndex++)
        //                {
        //                    dc_d.Images.Add(((MODI.Image)dc_o.Images[pageIndex]), null);
        //                }

        //                dc_o.Close();
        //            }


        //            dc_d.SaveAs(tempTiffPath);

        //            dc_d.Close();
        //            //System.Runtime.InteropServices.Marshal.ReleaseComObject((object)dc_o);
        //            //System.Runtime.InteropServices.Marshal.ReleaseComObject((object)dc_d);
        //        }
        //        catch (Exception ex)
        //        {
        //            throw ex;
        //        }
        //        finally {

        //            GC.Collect();
        //            GC.WaitForPendingFinalizers();
        //            System.Threading.Thread.Sleep(100);//wait for modi IO Handle release
        //        }
 
        //    }

        //    return tempTiffPath;
        //}

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            
            try
            {

            //Set it so page doesn't cache
            System.Web.UI.HtmlControls.HtmlMeta META = new System.Web.UI.HtmlControls.HtmlMeta();
            META.HttpEquiv = "Pragma";
            META.Content = "no-cache";
            Page.Header.Controls.Add(META);
            Response.Expires = -1;
            Response.CacheControl = "no-cache";

            //Get FilePath
            FilePath = Server.UrlDecode(Request.QueryString["File"].ToString());


            //if (ImpersonateLogon.impersonateValidUser(ConfigurationManager.AppSettings["ImpersonateUser"],
            //                                     ConfigurationManager.AppSettings["ImpersonateDomain"],
            //                                     ConfigurationManager.AppSettings["ImpersonatePassword"]))
            //{
                TiffImageLoad til = new TiffImageLoad(FilePath);

                this.Session.Add("ShowTiff", til.GetImageInstant());

            //    ImpersonateLogon.undoImpersonation();
            //}
            //else
            //{
            //    throw new Exception("Impersonate Logon Error!");
            //}


            if (FilePath != "")
            {
                //Determine Start/End Pages
                int StartPg = 1;
                if (Request.QueryString["StartPage"] != null)
                    StartPg = System.Convert.ToInt16(Request.QueryString["StartPage"]);
                int BigImgPg = StartPg;
                int EndPg = StartPg + (PagerSize - 1);
                if (EndPg > TotalTIFPgs)
                    EndPg = TotalTIFPgs;

                //Add/configure the thumbnails
                while (StartPg <= EndPg)
                {
                    Label lbl = new Label();
                    Label panel = new Label();

                    //if (StartPg % 4 == 0 && StartPg != 0) lbl.Text = "&nbsp; ";
                    //else 
                    lbl.Text = StartPg + "&nbsp;";
                    lbl.Attributes.Add("class", "num");
                    Image Img = new Image();
                    Img.BorderStyle = BorderStyle.Solid;
                    Img.BorderWidth = 1;
                    Img.Attributes.Add("onClick", "ChangePg(" + StartPg.ToString() + ");");
                    Img.Attributes.Add("onmouseover", "this.style.cursor='hand';");
                    Img.ImageUrl = "ViewImg.aspx?FilePath=" + Server.UrlEncode(FilePath) + "&Pg=" + (StartPg).ToString() + "&Height=" + DefaultThumbHieght.ToString() + "&Width=" + DefaultThumbWidth;
                   
                    panel.Controls.Add(Img);

                    panel.Controls.Add(lbl);
                    _plcImgsThumbs.Controls.Add(panel);
                    //_plcImgsThumbs.Controls.Add(Img);
                    //_plcImgsThumbs.Controls.Add(lbl);
                    StartPg++;
                }

                //Bind big img
                Image BigImg = new Image();
                BigImg.BorderStyle = BorderStyle.Solid;
                BigImg.BorderWidth = 1;
                BigImg.ID = "_imgBig";
                BigImg.ImageUrl = "ViewImg.aspx?View=1&FilePath=" + Server.UrlEncode(FilePath) + "&Pg=" + BigImgPg.ToString() + "&Height=" + DefaultBigHieght.ToString() + "&Width=" + DefaultBigWidth.ToString();
                //BigImg.ImageUrl = Server.UrlEncode(BigImg.ImageUrl);
                _plcBigImg.Controls.Add(BigImg);

                //Config actions
                _hlRot90.Attributes.Add("OnClick", "document.getElementById('_imgBig').src = 'ViewImg.aspx?View=1&FilePath=" + Server.UrlEncode(FilePath).ToString().Replace(@"\", "%5C") + "&Pg=" + BigImgPg.ToString() + "&Height=" + DefaultBigHieght.ToString() + "&Width=" + DefaultBigWidth.ToString() + "&Rotate=90';");
                _hlRot90.Attributes.Add("onmouseover", "this.style.cursor='hand';");

                _hlRot180.Attributes.Add("OnClick", "document.getElementById('_imgBig').src = 'ViewImg.aspx?View=1&FilePath=" + Server.UrlEncode(FilePath).ToString().Replace(@"\", "%5C") + "&Pg=" + BigImgPg.ToString() + "&Height=" + DefaultBigHieght.ToString() + "&Width=" + DefaultBigWidth.ToString() + "&Rotate=180';");
                _hlRot180.Attributes.Add("onmouseover", "this.style.cursor='hand';");

                _hlRot270.Attributes.Add("OnClick", "document.getElementById('_imgBig').src = 'ViewImg.aspx?View=1&FilePath=" + Server.UrlEncode(FilePath).ToString().Replace(@"\", "%5C") + "&Pg=" + BigImgPg.ToString() + "&Height=" + DefaultBigHieght.ToString() + "&Width=" + DefaultBigWidth.ToString() + "&Rotate=270';");
                _hlRot270.Attributes.Add("onmouseover", "this.style.cursor='hand';");

                _hlBig.Attributes.Add("OnClick", "document.getElementById('_imgBig').src = 'ViewImg.aspx?View=1&FilePath=" + Server.UrlEncode(FilePath).ToString().Replace(@"\", "%5C") + "&Pg=" + BigImgPg.ToString() + "&Height=" + (DefaultBigHieght + 400).ToString() + "&Width=" + (DefaultBigWidth + 400).ToString() + "';");
                _hlBig.Attributes.Add("onmouseover", "this.style.cursor='hand';");

                _hlSmall.Attributes.Add("OnClick", "document.getElementById('_imgBig').src = 'ViewImg.aspx?View=1&FilePath=" + Server.UrlEncode(FilePath).ToString().Replace(@"\", "%5C") + "&Pg=" + BigImgPg.ToString() + "&Height=" + (DefaultBigHieght).ToString() + "&Width=" + (DefaultBigWidth).ToString() + "';");
                _hlSmall.Attributes.Add("onmouseover", "this.style.cursor='hand';");

                //ConfigPagers
                //Config page 1 - whatever
                if ((TotalTIFPgs / PagerSize) >= 1)
                {
                    HyperLink _hl = new HyperLink();
                    Label lbl = new Label(); lbl.Text = "&nbsp;";
                    if (Request.Url.ToString().IndexOf("&StartPage=") >= 0)
                        _hl.NavigateUrl = Request.Url.ToString().Substring(0, Request.Url.ToString().IndexOf("&StartPage=")) + "&StartPage=1";
                    else
                        _hl.NavigateUrl = Request.Url.ToString() + "&StartPage=1";
                    if ((1 + PagerSize) > TotalTIFPgs)
                        _hl.Text = "1-" + TotalTIFPgs;
                    else
                        _hl.Text = "1-" + PagerSize;
                    _plcImgsThumbsPager.Controls.Add(_hl);
                    _plcImgsThumbsPager.Controls.Add(lbl);
                }
                //Config the rest of the page pagers
                for (int i = 1; i <= (TotalTIFPgs / PagerSize); i++)
                {
                    HyperLink _hl = new HyperLink();
                    Label lbl1 = new Label(); lbl1.Text = "&nbsp;";
                    if (Request.Url.ToString().IndexOf("&StartPage=") >= 0)
                        _hl.NavigateUrl = Request.Url.ToString().Substring(0, Request.Url.ToString().IndexOf("&StartPage=")) + "&StartPage=" + ((i * PagerSize) + 1).ToString();
                    else
                        _hl.NavigateUrl = Request.Url.ToString() + "&StartPage=" + ((i * PagerSize) + 1).ToString();
                    if (i == (TotalTIFPgs / PagerSize))
                        _hl.Text = ((i * PagerSize) + 1).ToString() + "-" + TotalTIFPgs;
                    else
                        _hl.Text = ((i * PagerSize) + 1).ToString() + "-" + (((i + 1) * PagerSize)).ToString();
                    _plcImgsThumbsPager.Controls.Add(_hl);
                    _plcImgsThumbsPager.Controls.Add(lbl1);
                }
            }
            else
            {
                Response.Write("Please provide a file path");
            }
        }
        catch (Exception exception)
        {
            //Response.Write(Workflow.Resource.Global.Readimageerror);
            Response.Write(exception.Message);
        }
        }

        public int TotalTIFPgs
        {
            get
            {
                //if (ImpersonateLogon.impersonateValidUser(ConfigurationManager.AppSettings["ImpersonateUser"],
                //                                     ConfigurationManager.AppSettings["ImpersonateDomain"],
                //                                     ConfigurationManager.AppSettings["ImpersonatePassword"]))
                //{
                //    if (ViewState["TotalTIFPgs"] == null)
                //    {
                //        TIF TheFile = new TIF(FilePath);
                //        ViewState["TotalTIFPgs"] = TheFile.PageCount;
                //        TheFile.Dispose();
                //    }

                //    ImpersonateLogon.undoImpersonation();
                //}
                //else
                //{
                //    throw new Exception("Impersonate Logon Error!");
                //}

                try
                {
                    if (ViewState["TotalTIFPgs"] == null)
                    {

                        List<byte[]> msList = (List<byte[]>)this.Session["ShowTiff"];

                        ViewState["TotalTIFPgs"] = msList.Count;
                    }
                }
                catch (Exception)
                {

                    ViewState["TotalTIFPgs"] = 0;
                }
                


                return System.Convert.ToInt16(ViewState["TotalTIFPgs"]);
            }
            set
            {
                ViewState["TotalTIFPgs"] = value;
            }
        }

        public String FilePath
        {
            get
            {
                if (ViewState["FilePath"] == null)
                {
                    return "";
                }
                return ViewState["FilePath"].ToString();
            }
            set
            {
                ViewState["FilePath"] = value;
            }
        }
    }
}